<template>
  <div class="app-container">
        <el-form :inline="true" size="mini"   @keyup.enter.native="getContractStatisticsByDept()">
            <el-form-item label="所属企业">
                <el-select
                        v-model="companyId"
                        clearable
                        placeholder="请输入企业名称关键词"
                        :loading="loading"
                        style="width: 240px;"  >
                    <el-option
                            v-for="item in companyList"
                            :key="item.id"
                            :label="item.name"
                            :value="item.id">
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="所属月份">
                <el-date-picker
                        v-model="dateRange"
                        type="monthrange"
                        align="right"
                        unlink-panels
                        value-format="yyyy-MM-dd"
                        range-separator="至"
                        :default-value="dateRange"
                        start-placeholder="开始月份"
                        end-placeholder="结束月份"
                        :picker-options="pickerOptions">
                </el-date-picker>
            </el-form-item>
            <el-form-item>
                <el-button @click="getContractStatisticsByDept">{{ $t('query') }}</el-button>
            </el-form-item>
            <el-form-item>
                <el-button v-hasPermi="['sys:ContractStatisticsByDept:export']" type="primary" @click="exportExcel()">{{ $t('export') }}</el-button>
            </el-form-item>
        </el-form>
        <el-table
                id="integration-table"
                size="mini"
                v-loading="dataListLoading"
                :data="dataList"
                :span-method="objectSpanMethod"
                border
                stripe
                style="width: 100%;">
            <el-table-column prop="deptParentName" label="部门团队" header-align="center" align="center" width="180"/>
            <el-table-column prop="companyName" label="企业名称" header-align="center" align="center"/>
            <el-table-column prop="salesmanName" label="业务员" header-align="center" align="center" width="120"/>
            <el-table-column prop="totalCount" label="备案总数" header-align="center" align="center" width="120"/>
            <el-table-column prop="totalAmount" label="备案金额(元)" header-align="center" align="center"  :formatter="moneyFormat"/>
            <el-table-column prop="failCount" label="作废笔数" header-align="center" align="center" width="120"/>
            <el-table-column prop="failTotalAmount" label="作废金额(元)" header-align="center" align="center"  :formatter="moneyFormat" />
            <el-table-column prop="completedCount" label="成功笔数" header-align="center" align="center" width="120"/>
            <el-table-column prop="totalContractAmount" label="成功金额(元)" header-align="center" align="center" :formatter="moneyFormat"/>
            <el-table-column label="操作" align="center" width="120" class-name="small-padding fixed-width">
                <template slot-scope="scope">
                    <el-button size="mini" type="text" icon="el-icon-document" @click="handleContractListDetails(scope.row)">查看明细</el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- 分页 -->
        <el-pagination
                slot="footer"
                :current-page="page"
                :page-sizes="[10, 20, 50, 100]"
                :page-size="limit"
                :total="total"
                layout="total, sizes, prev, pager, next, jumper"
                @size-change="pageSizeChangeHandle"
                @current-change="pageCurrentChangeHandle">
        </el-pagination>


        <el-dialog title="签署完成合同明细" :visible.sync="contractListOpen" width="80%" append-to-body>
            <el-table
                    size="mini"
                    v-loading="loading"
                    :data="contractList"
                    border
                    stripe
                    style="width: 100%;">
                <!--            <el-table-column type="selection" header-align="center" align="center" width="50"/>-->
                <el-table-column prop="clientName" :label="$t('contract.clientName')" header-align="center" align="center" show-overflow-tooltip/>
                <el-table-column prop="contractNo" :label="$t('contract.contractNo')" header-align="center" align="center">
                </el-table-column>
                <el-table-column prop="contractName" :label="$t('contract.contractName')" header-align="center" align="center">
                </el-table-column>
                <el-table-column prop="customerName" :label="$t('contract.customerName')" header-align="center" align="center" width="100"/>
                <el-table-column prop="amount" :label="$t('contract.amount')" header-align="center" align="center" width="140" :formatter="moneyFormat"/>
                <el-table-column prop="contractAmount" :label="$t('contract.contractAmount')" header-align="center" align="center" width="140" :formatter="moneyFormat"/>
                <el-table-column prop="status" :label="$t('contract.status')" header-align="center" align="center" width="100">
                    <template slot-scope="scope">
                        <el-tag v-if="scope.row.status === '0'" size="mini" type="info">{{ $t('contract.status0') }}</el-tag>
                        <el-tag v-else-if="scope.row.status === '1'" size="mini" type="warning">{{ $t('contract.status1') }}
                        </el-tag>
                        <el-tag v-else-if="scope.row.status === '2'" size="mini">{{ $t('contract.status2') }}</el-tag>
                        <el-tag v-else-if="scope.row.status === '3'" size="mini" type="warning">{{ $t('contract.status3') }}
                        </el-tag>
                        <el-tag v-else-if="scope.row.status === '4'" size="mini" type="success">{{ $t('contract.status4') }}
                        </el-tag>
                        <el-tag v-else-if="scope.row.status === '5'" size="mini" type="danger">{{ $t('contract.status5') }}
                        </el-tag>
                        <el-tag v-else-if="scope.row.status === '6'" size="mini" type="danger">{{ $t('contract.status6') }}
                        </el-tag>
                    </template>
                </el-table-column>
<!--                <el-table-column prop="isPay" label="支付状态" header-align="center" align="center" width="120">-->
<!--                    <template slot-scope="scope">-->
<!--                        <el-tag v-if="scope.row.isPay === 0" size="mini" type="danger">未支付</el-tag>-->
<!--                        <el-tag v-else-if="scope.row.isPay === 1" size="mini" type="success">已支付</el-tag>-->
<!--                        <el-tag v-else-if="scope.row.isPay === 2" size="mini" type="warning">退款中</el-tag>-->
<!--                        <el-tag v-else-if="scope.row.isPay === 3" size="mini" type="info">已退款</el-tag>-->
<!--                        <el-tag v-else-if="scope.row.isPay === 4" size="mini" type="info">拒绝退款</el-tag>-->
<!--                    </template>-->
<!--                </el-table-column>-->
<!--                <el-table-column prop="datumStatus" :label="$t('contract.datumStatus')" header-align="center" align="center" width="120">-->
<!--                    <template slot-scope="scope">-->
<!--                        <el-tag v-if="scope.row.datumStatus === 0" size="mini" type="danger">{{ $t('contract.datumStatus0')}}</el-tag>-->
<!--                        <el-tag v-else-if="scope.row.datumStatus === 1" size="mini" type="success">{{$t('contract.datumStatus1') }}</el-tag>-->
<!--                    </template>-->
<!--                </el-table-column>-->
                <el-table-column prop="creator" :label="$t('createBy')" header-align="center" align="center" width="80"/>
                <el-table-column prop="createTime" :label="$t('createTime')" header-align="center" align="center" width="90"/>
            </el-table>
            <!-- 分页 -->
            <pagination
                    v-show="contractListTotal>0"
                    :total="contractListTotal"
                    :page.sync="queryParams.current"
                    :limit.sync="queryParams.size"
                    @pagination="getCompletedContractList"
            />
        </el-dialog>

    </div>
</template>

<script>
    import { listContract} from "@/api/zfw/contract/contract";

    export default {
        name: "ContractStatisticsByDept",
        data() {

            return {
                dataList:[],
                companyList: [],
                contractList:[],
                contractListOpen:false,
                page: 1, // 当前页码
                limit: 20, // 每页数
                total: 0,
                contractListTotal:0,
                loading: false,
                dataListLoading:false,
                companyId:'',
                columns: [
                    {
                        label: 'ID',
                        prop: 'id'
                    },
                    {
                        label: '企业名称',
                        prop: 'companyName'
                    },
                    {
                        label:'总数',
                        prop: 'totalCount'
                    },
                    {
                        label: '成功数量',
                        prop: 'completedCount'
                    },
                    {
                        label: '进行中数量',
                        prop: 'doingCount'
                    },
                    {
                        label: '废弃数量',
                        prop: 'failCount'
                    }
                ],
                // 日期范围
                dateRange: [],
                pickerOptions: {
                    shortcuts: [{
                        text: '本月',
                        onClick(picker) {
                            picker.$emit('pick', [new Date(), new Date()]);
                        }
                    }, {
                        text: '今年至今',
                        onClick(picker) {
                            const end = new Date();
                            const start = new Date(new Date().getFullYear(), 0);
                            picker.$emit('pick', [start, end]);
                        }
                    }, {
                        text: '最近六个月',
                        onClick(picker) {
                            const end = new Date();
                            const start = new Date();
                            start.setMonth(start.getMonth() - 6);
                            picker.$emit('pick', [start, end]);
                        }
                    }]
                },
                // 查询参数
                queryParams: {
                    current: 1,
                    size: 10,
                    contractNo: null,
                    contractName: null,
                    status: null,
                    amount: null,
                    contractAmount: null,
                    clientId: null,
                    createBy:null,
                    clientName: null,
                    customerName: null,
                    createTime: null,
                },
            }
        },
        methods: {
            init() {
                if(this.dateRange.length===0){
                    let currDate = this.$moment(new Date());
                    this.dateRange.push(this.$moment(currDate.startOf("month").valueOf()).format('YYYY-MM-DD')) ;
                    this.dateRange.push(this.$moment(currDate.endOf("month").valueOf()).format('YYYY-MM-DD'));
                }
                this.getContractStatisticsByDept();
                this.getCompanyList("");
            },

            getContractStatisticsByDept: function(){
                let params = {
                    current: this.page,
                    size: this.limit ,
                    id: this.companyId
                };
                if(this.dateRange == null || this.dateRange.length === 0){
                    let currDate = this.$moment(new Date());
                    this.dateRange = [];
                    this.dateRange.push(this.$moment(currDate.startOf("month").valueOf()).format('YYYY-MM-DD')) ;
                    this.dateRange.push(this.$moment(currDate.endOf("month").valueOf()).format('YYYY-MM-DD'));
                }else{
                    let startDate = this.$moment(this.dateRange[0]);
                    let endDate = this.$moment(this.dateRange[1]);
                    this.dateRange[0] = this.$moment(startDate.startOf("month").valueOf()).format('YYYY-MM-DD') ;
                    this.dateRange[1] = this.$moment(endDate.endOf("month").valueOf()).format('YYYY-MM-DD') ;
                }

                this.$http.get('/manager/statistics/statisticsContractByDept', this.addDateRange(params, this.dateRange)).then(res => {
                    this.dataList = res.data.records;
                    this.total = res.data.total;
                }).catch(() => {
                })
            },

            // 分页, 每页条数
            pageSizeChangeHandle (val) {
                this.page = 1;
                this.limit = val;
                this.getContractStatisticsByDept();
            },
            // 分页, 当前页
            pageCurrentChangeHandle (val) {
                this.page = val;
                this.getContractStatisticsByDept();
            },

            remoteMethod(query) {
                if (query !== '') {
                    this.loading = true;
                    this.getCompanyList(query);
                } else {
                    this.companyList = [];
                }
            },
            moneyFormat(row,column){
              return  this.formatMoney(row[column.property]);
            },

            formatMoney(number, decimals = 2, decPoint = '.', thousandsSep = ','){
                  number = (number + '').replace(/[^0-9+-Ee.]/g, '')
                  let n = !isFinite(+number) ? 0 : +number
                  let prec = !isFinite(+decimals) ? 0 : Math.abs(decimals)
                  let sep = (typeof thousandsSep === 'undefined') ? ',' : thousandsSep
                  let dec = (typeof decPoint === 'undefined') ? '.' : decPoint
                  let s = ''
                  let toFixedFix = function (n, prec) {
                      let k = Math.pow(10, prec)
                      return '' + Math.ceil(n * k) / k
                  }
                  s = (prec ? toFixedFix(n, prec) : '' + Math.round(n)).split('.')
                  let re = /(-?\d+)(\d{3})/
                  while (re.test(s[0])) {
                      s[0] = s[0].replace(re, '$1' + sep + '$2')
                  }
                  if ((s[1] || '').length < prec) {
                      s[1] = s[1] || ''
                      s[1] += new Array(prec - s[1].length + 1).join('0')
                  }
                  return s.join(dec)
            },
            // 获企业客户所列表
            getCompanyList(queryName) {
                return this.$axios.get('/manager/company/getMineOfCompanyList', {
                    params: {
                        order: 'ASC',
                        orderField: 'createTime',
                        current: 1,
                        size: 20,
                        listMode: true,
                        queryItems: 'name,LIKE,' + queryName
                    }
                }).then(res => {
                    this.loading = false;
                    this.companyList = res
                }).catch(() => {
                })
            },

            objectSpanMethod({ row, column, rowIndex, columnIndex }) {  //表格合并行
                if(columnIndex === 0 ) {
                    // this.tableData  修改
                    const _row = (this.flitterData(this.dataList,'deptParentName').one)[rowIndex];
                    const _col = _row > 0 ? 1 : 0;
                    return {
                        rowspan: _row,
                        colspan: _col
                    };
                }else if(columnIndex === 1 ) {
                    // this.tableData  修改
                    const _row = (this.flitterData(this.dataList,'companyName').one)[rowIndex];
                    const _col = _row > 0 ? 1 : 0;
                    return {
                        rowspan: _row,
                        colspan: _col
                    };
                }
            },

            flitterData(arr,lable){
                let spanOneArr = []
                let concatOne = 0
                arr.forEach((item,index)=>{
                    if(index === 0){
                        spanOneArr.push(1);
                    }else{
                        //name 修改
                        if(item[lable] === arr[index - 1][lable]){ //第一列需合并相同内容的判断条件
                            spanOneArr[concatOne] += 1;
                            spanOneArr.push(0);
                        }else{
                            spanOneArr.push(1);
                            concatOne = index;
                        };
                    }
                });
                return  {
                    one: spanOneArr,
                }
            },

            //
            handleContractListDetails(row){
                this.queryParams.clientId = row.id;
                this.queryParams.createBy = row.createBy;
                this.getCompletedContractList();
            },

            //获取合同完成的列表
            getCompletedContractList(){
                this.loading = true;
                this.queryParams.status = 4;
                listContract(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
                    this.contractListOpen = true;
                    this.contractList = response.data.records;
                    this.contractListTotal = response.data.total;
                    this.loading = false;
                });

            },

            // 定义导出Excel表格事件
            exportExcel () {
                /* 从表生成工作簿对象 */
                var wb =this.$XLSX.utils.table_to_book(document.querySelector('#integration-table'))
                /* 获取二进制字符串作为输出 */
                var wbout = this.$XLSX.write(wb, {
                    bookType: 'xlsx',
                    bookSST: true,
                    type: 'array'
                })
                try {
                    // Blob 对象表示一个不可变、原始数据的类文件对象。
                    // Blob 表示的不一定是JavaScript原生格式的数据。
                    // File 接口基于Blob，继承了 blob 的功能并将其扩展使其支持用户系统上的文件。
                    // 返回一个新创建的 Blob 对象，其内容由参数中给定的数组串联组成。
                    this.$FileSaver.saveAs(
                        new Blob([wbout], { type: 'application/octet-stream' }),
                        // 设置导出文件名称
                        '部门合同统计.xlsx')
                } catch (e) {
                    if (typeof console !== 'undefined') console.log(e, wbout)
                } return wbout
            },

            // exportExcel() {
            //     this.$export.excel({
            //         columns: this.columns,
            //         data: this.dataList,
            //         header: '企业合同数量统计',
            //         merges: ['A1', 'E1']
            //     }).then(() => {
            //         this.$message({
            //             message: '导出表格成功',
            //             type: 'success'
            //         });
            //     })
            // }

        },
        mounted() {
            this.init();
        }
    }
</script>

<style lang="scss" scoped>
    .inner {
        position: absolute;
        top: 20px;
        right: 20px;
        bottom: 20px;
        left: 20px;
    }

</style>
